package org.mv.mm.docs.nodes;

import java.beans.PropertyChangeEvent;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.mv.mm.api.Doc;
import org.mv.mm.api.capabilities.IReloadableDocCapability;
import org.mv.mm.api.data.IDataProvider;
import org.openide.nodes.*;

/**
 *
 * @author Martin
 */
class DocRootNodeChildFactory extends ChildFactory<Doc> implements NodeListener {

  private IDataProvider dataProvider;
  private static final Logger logger = Logger.getLogger(DocRootNodeChildFactory.class.getName());

  /**
   * Called by root node (root doc).
   *
   * @param dataProvider IDataProvider
   */
  public DocRootNodeChildFactory(IDataProvider dataProvider) {
    this.dataProvider = dataProvider;
  }

  @Override
  protected boolean createKeys(List<Doc> list) {
    if (!Thread.interrupted()) { // should be called for some occasions of closed node etc.
      // get this ability from the lookup ...
      IReloadableDocCapability r = dataProvider.getLookup().lookup(IReloadableDocCapability.class);
      // ... and  use the ability
      if (r != null) {
        try {
          // Reloads docs
          r.reload();

          // Now populate the list of child entities...
          list.addAll(dataProvider.getDocs());


        } catch (Exception e) {
          logger.log(Level.WARNING, null, e); //TODO provide a message from Bundle
        }
      }
    }
    // And return true since we're all set
    return true;
  }

  @Override
  protected Node createNodeForKey(Doc key) {
    DocNode docNode = new DocNode(key, dataProvider);

    docNode.addNodeListener(this);
    return docNode;
  }

  @Override
  public void childrenAdded(NodeMemberEvent nme) {
    System.out.println("Doc childrenAdded");
    //TODO or nothing
  }

  @Override
  public void childrenRemoved(NodeMemberEvent nme) {
    System.out.println("Doc childrenRemoved");
    //TODO or nothing
  }

  @Override
  public void childrenReordered(NodeReorderEvent nre) {
    System.out.println("Doc childrenReordered");
    //TODO or nothing
  }

  @Override
  public void nodeDestroyed(NodeEvent ne) {
    refresh(true);
  }

  @Override
  public void propertyChange(PropertyChangeEvent evt) {
    //TODO or nothing
  }
}
